package tech.runchen.gz5055.oms.modules.system.controller;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import tech.runchen.gz5055.oms.common.base.AbstractController;
import tech.runchen.gz5055.oms.common.utils.Result;
import tech.runchen.gz5055.oms.common.utils.StringUtils;
import tech.runchen.gz5055.oms.modules.system.entity.FingerprintEntity;
import tech.runchen.gz5055.oms.modules.system.entity.UserEntity;
import tech.runchen.gz5055.oms.modules.system.form.SysLoginForm;
import tech.runchen.gz5055.oms.modules.system.form.SysRegisterForm;
import tech.runchen.gz5055.oms.modules.system.service.IFingerprintService;
import tech.runchen.gz5055.oms.modules.system.service.IUserService;
import tech.runchen.gz5055.oms.security.service.LoginService;

import java.util.List;
import java.util.Map;


/**
 * @author zzj
 */
@Api(tags = "管理平台 - 用户登录控制器")
@RestController
public class SysLoginController extends AbstractController {

    @Autowired
    private LoginService loginService;
    @Autowired
    private IUserService userService;
    @Autowired
    private IFingerprintService fingerprintService;

    @ApiOperation("登录")
    @PostMapping("/sys/login")
    public Result login(@RequestBody SysLoginForm form) {
        String token;
        if (StringUtils.isNotBlank(form.getPsChar())) {
            token = loginService.login(form.getPsChar());
        } else {
            token = loginService.login(form.getUsername(), form.getPassword());
        }
        return Result.success().put("token", token);
    }

    @ApiOperation("注册")
    @PostMapping("/sys/register")
    public Result register(@RequestBody SysRegisterForm form) {
        UserEntity user = userService.queryByUserName(form.getUserName());
        if (user != null) {
            return Result.error("用户信息已存在");
        }
        user = new UserEntity();
        user.setNickName(form.getNickName());
        user.setUserName(form.getUserName());
        user.setPassword(form.getPassword());
        user.setType(form.getType());
        boolean ret = userService.saveUser(user);
        if (StringUtils.isNotBlank(form.getPsChar()) && fingerprintService.checkFingerprint(form.getPsChar()) == null) {
            FingerprintEntity fingerprint = new FingerprintEntity();
            fingerprint.setUserId(user.getId());
            fingerprint.setPsChar(form.getPsChar());
            fingerprintService.saveFingerprint(fingerprint);
        }
        return toResult(ret);
    }

    @ApiOperation("退出登录")
    @PostMapping("/sys/logout")
    public Result logout() {
        loginService.logout(getLoginUser());
        return Result.success();
    }

}
